package com.wzy.mall.web.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wzy.mall.model.vo.ResultVO;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/admin/*")
public class ApplicationFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        // 设置编码格式
        request.setCharacterEncoding("utf8");
        response.setContentType("text/html;charset=utf8");


        // 设置响应的授权，解决跨域问题
        ServletContext servletContext = request.getServletContext();
        String origin = (String) servletContext.getAttribute("origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,Content-Type");
        response.setHeader("Access-Control-Allow-Credentials","true");

        // 后台拦截，部分拦截（除了Login接口以外都需要登陆验证
        // OPTIONS请求因为是试探性请求，所以不拦截
        if(!"OPTIONS".equalsIgnoreCase(request.getMethod())) {
            // /api/admin/admin/login   其他全部需要验证权限
            String requestURI = request.getRequestURI();
            if(!"/api/admin/admin/login".equals(requestURI)){
                //验证是否登录
                Object email = request.getSession().getAttribute("email");
                if(email == null){
                    //没有登录  拦截
                    response.getWriter().println(new ObjectMapper().writeValueAsString(ResultVO.error("当前接口仅登录后才可以访问")));
                    return;
                }
            }
        }

        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
